package com.martini.satoken01.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.martini.satoken01.model.AjaxJson;
import com.martini.satoken01.service.system.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 账号退出登录
 *
 * @author martini at 2021/12/20 17:35
 */
@Slf4j
@RestController
@RequestMapping("/logout")
public class LogoutController {

    private final UserService userService;

    public LogoutController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping
    @SaCheckLogin
    public AjaxJson logout(@RequestHeader("User-Agent") String uaStr) {
        UserAgent ua = UserAgentUtil.parse(uaStr);
        String device = ua.getPlatform().toString();
        long loginIdAsLong = StpUtil.getLoginIdAsLong();
        StpUtil.logout(loginIdAsLong, device);
        this.userService.offline(loginIdAsLong, device);
        return AjaxJson.success();
    }

}
